package com.las.bot.cq;

import com.las.bot.common.Constant;
import com.las.bot.dao.ReWardDao;
import com.las.cq.event.message.CQDiscussMessageEvent;
import com.las.cq.event.message.CQPrivateMessageEvent;
import com.las.cq.event.notice.CQFriendAddNoticeEvent;
import com.las.cq.event.request.CQFriendRequestEvent;
import com.las.cq.robot.CQPlugin;
import com.las.cq.robot.CoolQ;
import com.model.ReWard;
import com.utils.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class ReWardPlugin extends CQPlugin {

    private static Logger logger = LoggerFactory.getLogger(ReWardPlugin.class);

    @Autowired
    private ReWardDao reWardDao;


    @Override
    public int onPrivateMessage(CoolQ cq, CQPrivateMessageEvent event) {
        return reWard(cq, event.getUserId(), event.getMessage(), Constant.MESSAGE_TYPE_PRIVATE);
    }


    @Override
    public int onDiscussMessage(CoolQ cq, CQDiscussMessageEvent event) {
        return reWard(cq, event.getUserId(), event.getMessage(), Constant.MESSAGE_TYPE_DISCUSS);
    }


    private int reWard(CoolQ cq, long userId, String msg, int type) {
        if (msg.startsWith("&#91;转账&#93;")) {
            String money = msg.split("已转账成功")[0].replaceAll("&#91;转账&#93;", "").trim();
            logger.info(userId + " 转账了 " + money);
            String orderId;
            try {
                ReWard re = new ReWard();
                orderId = IdUtil.nextId();
                re.setOrderId(orderId);
                re.setCreateTime(new Date());
                re.setSysId(null);
                re.setUserId(userId);
                re.setMoney(money);
                reWardDao.saveOrUpdate(re);
                if (type == Constant.MESSAGE_TYPE_PRIVATE) {
                    cq.sendPrivateMsg(userId, "流水号：" + orderId, false);
                } else if (type == Constant.MESSAGE_TYPE_DISCUSS) {
                    cq.sendDiscussMsg(userId, "流水号：" + orderId, false);
                }
                return MESSAGE_BLOCK;
            } catch (Exception e) {
                logger.error(e.toString());
            }
        }

        return MESSAGE_IGNORE;
    }
}
